package com.wusuowei.auth.config;

import com.wusuowei.auth.security.exception.MyWebResponseExceptionTranslator;
import com.wusuowei.auth.service.impl.SecurityUserServiceImpl;
import com.wusuowei.auth.security.JwtTokenEnhancer;
import com.wusuowei.common.config.WuSuoWeiConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;


/**
 * @description 授权服务器配置
 * @author LGY
 * @date 2023/03/31 00:23
 * @version 1.0.0
 */
@RefreshScope
@Configuration
@EnableAuthorizationServer//开启授权服务器
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private WuSuoWeiConfig wuSuoWeiConfig;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private SecurityUserServiceImpl userService;
    @Autowired
    // @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        //设置jwt增强内容
        TokenEnhancerChain chain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        chain.setTokenEnhancers(delegates);

        //默认除了密码模式都实现了，这里配置密码模式
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService) // 配置自定义的用户权限数据，不配置会导致token无法刷新
                //accessToken转成JWTtoken
                .tokenStore(tokenStore) // 配置token存储
                .accessTokenConverter(jwtAccessTokenConverter)
                .exceptionTranslator(new MyWebResponseExceptionTranslator()) // 自定义异常返回
                .tokenEnhancer(chain)//扩展jwt存储的内容

        ;

    }

    /**
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")// appid
                .secret(passwordEncoder.encode("112233"))// appsecret
                //.redirectUris("http://www.baidu.com") // 回调地址
                .redirectUris("http://localhost:8080/login") //回调地址 重定向去你请求前被拦截的地址
                .scopes("all")// 作用域
                .accessTokenValiditySeconds(wuSuoWeiConfig.getExpire())//设置accessToken失效时间为60秒
                .refreshTokenValiditySeconds(wuSuoWeiConfig.getRefreshTokenexpire())//刷新令牌的失效时间
                .autoApprove(true)//自动授权
                // 资源的id
                .resourceIds("wusuowei")
                // 授权类型：授权码
                .authorizedGrantTypes("authorization_code", "password", "implicit","client_credentials","refresh_token")
        ;
    }


    //令牌端点的安全配置
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .tokenKeyAccess("permitAll()")                    //oauth/token_key是公开  开启/oauth/token_key验证端口无权限访问
                .checkTokenAccess("isAuthenticated()")                  //oauth/check_token  开启/oauth/check_token验证端口认证权限访问
                .allowFormAuthenticationForClients();            //表单认证（申请令牌） 请求/oauth/token的，如果不配置这个/oauth/token访问就会显示没有认证

    }


}
